package com.zyh.kaoshi.test5;

import java.io.*;
import java.util.Scanner;

/**
 * @Author zyh
 * @Date 2024/8/10 11:46
 * @Description Test5.java  Test.txt
 */

public class Test5 {
    public static void main(String[] args) {
        File file = new File("day13-code/src/com/zyh/kaoshi/test5");
        Scanner input = new Scanner(System.in);
        System.out.println("请输入一个文件名");
        String fileName = input.next();
        File[] files = file.listFiles();
        //判断是否存在
        boolean flag = false;
        for (File ziFile : files) {
            if (ziFile.getName().equals(fileName)) {
                flag = true;
            }
        }
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            if (flag) {
                //存在则遍历所有的文件，拿到每个子文件
                for (File ziFile : files) {
                    //判断名字是否相同
                    if (ziFile.getName().equals(fileName)) {
                        //创建新文件
                        File newFile = new File(file.getPath() + "copy_" + fileName);
                        br = new BufferedReader(new FileReader(ziFile.getPath()));
                        bw = new BufferedWriter(new FileWriter(newFile.getPath()));
                        char[] car=new char[1024];
                        int len=-1;
                        while ((len = br.read(car)) != -1) {
                            bw.write(car,0,len);
                        }
                    }
                }
            } else {
                System.out.println("文件不存在！");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bw.close();
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
